<template>
  <el-table v-bind="$attrs" :data="value" :id="id">
    <template slot="empty">
      <slot name="empty" />
    </template>
    <el-table-column class-name="wards-move" label="顺序" width="60">
      <template slot-scope="{ row, $index }">
        <img class="dragIcon" src="./drag.png" />
      </template>
    </el-table-column>
    <slot />
  </el-table>
</template>

<script>
import Sortable from 'sortablejs'
export default {
  name: 'SortTable',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    id: {
      type: String,
      default: 'sortTable'
    },
    // 排序字段
    sortField: {
      type: String,
      default: 'sortId'
    }
  },
  mounted() {
    this.rowDrop()
  },
  methods: {
    rowDrop() {
      this.$nextTick(() => {
        const tbody = document.querySelector(`#${this.id} tbody`)
        Sortable.create(tbody, {
          handle: '.wards-move',
          animation: 150,
          onEnd: ({ oldIndex, newIndex }) => {
            // 缓存数据数组赋值给实际数据数组
            this.value.splice(newIndex, 0, this.value.splice(oldIndex, 1)[0])
            const tableData = this.value.slice(0)
            this.$emit('input', [])
            this.$nextTick(() => {
              this.$emit('input', tableData)
              tableData.forEach((item, index) => {
                this.$set(item, this.sortField, index + 1)
              })
              this.$emit('change', tableData)
            })
          }
        })
      })
    }
  }
}
</script>

<style scoped>
  .dragIcon{
    width: 20px;
    height: 20px;
    cursor: pointer;
    padding-top: 7px;
  }
</style>
